import 'dart:convert';
import 'dart:typed_data';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: '数据转换工具（增强版）',
      theme: ThemeData(primarySwatch: Colors.blue),
      home: ConversionTool(),
    );
  }
}

class ConversionTool extends StatefulWidget {
  @override
  _ConversionToolState createState() => _ConversionToolState();
}

class _ConversionToolState extends State<ConversionTool> {
  final TextEditingController _inputController = TextEditingController();
  final TextEditingController _outputController = TextEditingController();
  String _errorMessage = '';

  void _convert(String operation) {
    try {
      final input = _inputController.text.trim();
      Uint8List bytes;
      String result;

      switch (operation) {
        case 'hexToBase64':
          bytes = _hexToBytes(input);
          result = base64Encode(bytes);
          break;
        case 'base64ToHex':
          bytes = base64Decode(input);
          result = _bytesToHex(bytes);
          break;
        case 'hexToUint8':
          bytes = _hexToBytes(input);
          result = _bytesToHexList(bytes);  // 修改为十六进制列表
          break;
        case 'uint8ToHex':
          bytes = _commaStringToBytes(input);
          result = _bytesToHex(bytes);
          break;
        case 'base64ToUint8':
          bytes = base64Decode(input);
          result = _bytesToHexList(bytes); // 修改为十六进制列表
          break;
        case 'uint8ToBase64':
          bytes = _commaStringToBytes(input);
          result = base64Encode(bytes);
          break;
        default:
          result = '未知操作';
      }

      setState(() {
        _outputController.text = result;
        _errorMessage = '';
      });
    } catch (e) {
      setState(() => _errorMessage = '转换失败: ${e.toString()}');
    }
  }

  // 十六进制字符串转字节数组
  Uint8List _hexToBytes(String hex) {
    if (hex.isEmpty) throw FormatException("输入不能为空");
    if (hex.length % 2 != 0) throw FormatException("十六进制长度必须为偶数");
    return Uint8List.fromList(
        List.generate(hex.length ~/ 2, (i) => int.parse(hex.substring(i*2, i*2+2), radix:16))
    );
  }

  // 字节数组转连续十六进制字符串
  String _bytesToHex(Uint8List bytes) {
    return bytes.map((b) => b.toRadixString(16).padLeft(2, '0').toUpperCase()).join('');
  }

  // 字节数组转逗号分隔十六进制字符串（新增方法）
  String _bytesToHexList(Uint8List bytes) {
    return bytes.map((b) => '0x${b.toRadixString(16).padLeft(2, '0').toUpperCase()}').join(', ');
  }

  // 支持十六进制和十进制的解析（改进方法）
  Uint8List _commaStringToBytes(String input) {
    final parts = input.split(',').map((s) => s.trim()).toList();
    final bytes = <int>[];

    for (final part in parts) {
      if (part.startsWith('0x')) {
        // 解析十六进制
        final hex = part.substring(2);
        if (hex.isEmpty) throw FormatException('无效的十六进制值: $part');
        final value = int.tryParse(hex, radix: 16);
        if (value == null || value < 0 || value > 255) {
          throw FormatException('无效的字节值: $part');
        }
        bytes.add(value);
      } else {
        // 解析十进制
        final value = int.tryParse(part);
        if (value == null || value < 0 || value > 255) {
          throw FormatException('无效的字节值: $part');
        }
        bytes.add(value);
      }
    }
    return Uint8List.fromList(bytes);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('数据转换工具（增强版）')),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          children: [
            TextField(
              controller: _inputController,
              decoration: const InputDecoration(
                labelText: '输入内容',
                border: OutlineInputBorder(),
                hintText: '根据操作类型输入相应格式',
              ),
              maxLines: 3,
            ),
            const SizedBox(height: 15),
            Wrap(
              spacing: 8,
              runSpacing: 8,
              children: [
                _buildOperationButton('hex转base64'),
                _buildOperationButton('base64转hex'),
                _buildOperationButton('hex转uint8'),
                _buildOperationButton('uint8转hex'),
                _buildOperationButton('base64转uint8'),
                _buildOperationButton('uint8转base64'),
              ],
            ),
            const SizedBox(height: 20),
            TextField(
              controller: _outputController,
              decoration: InputDecoration(
                labelText: '输出结果',
                border: const OutlineInputBorder(),
                suffixIcon: IconButton(
                  icon: const Icon(Icons.content_copy),
                  onPressed: () => Clipboard.setData(
                      ClipboardData(text: _outputController.text)
                  ).then((_) => ScaffoldMessenger.of(context).showSnackBar(
                      const SnackBar(content: Text('已复制到剪贴板'))
                  )),
                ),
              ),
              readOnly: true,
              maxLines: 3,
            ),
            if (_errorMessage.isNotEmpty)
              Padding(
                padding: const EdgeInsets.only(top: 8.0),
                child: Text(
                  _errorMessage,
                  style: const TextStyle(color: Colors.red, fontSize: 12),
                ),
              ),
          ],
        ),
      ),
    );
  }

  Widget _buildOperationButton(String text) {
    final operations = {
      'hex转base64': 'hexToBase64',
      'base64转hex': 'base64ToHex',
      'hex转uint8': 'hexToUint8',
      'uint8转hex': 'uint8ToHex',
      'base64转uint8': 'base64ToUint8',
      'uint8转base64': 'uint8ToBase64',
    };

    return ElevatedButton(
      style: ElevatedButton.styleFrom(
        padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 10),
      ),
      onPressed: () => _convert(operations[text]!),
      child: Text(text),
    );
  }
}